import Taro, { Component } from '@tarojs/taro'
import { View, Swiper, SwiperItem, ScrollView } from '@tarojs/components'
import './index.scss'
import GRootPage from "../../components/RootPage";
import GTabs from "../../components/Tabs";
import GCardList from "../../components/CardList";
import { parseParams } from "../../utils";

export default class Home extends Component {

  lastTab = 0 // 上一个 tab，需要将数据清除
  allowSwitch = true // 是否允许通过 tab 点击切换 swiper
  queryParams = {
    pageSize: 15,
    currentPage: 1
  }
  state = {
    bannerList: [
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589627743542&di=b1173cc80ddb65f687fa607dffb82e9d&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201311%2F16%2F144926tztx5ytqwt4pqqwp.jpg',
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589627743542&di=b1173cc80ddb65f687fa607dffb82e9d&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201311%2F16%2F144926tztx5ytqwt4pqqwp.jpg',
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589627743542&di=b1173cc80ddb65f687fa607dffb82e9d&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201311%2F16%2F144926tztx5ytqwt4pqqwp.jpg'
    ],
    currentIndex: 1,
    tabs: [
      { label: '关注' },
      { label: '推荐' },
      // { label: '周边' },
    ],
    data: {}
  }

  onTabClick = nextTab => {
    const { currentIndex } = this.state
    if (nextTab === currentIndex || !this.allowSwitch) {
      // 不做操作
      return
    }
    this.allowSwitch = false
    this.lastTab = currentIndex
    this.state.currentIndex = nextTab
    this.setState({})
  }

  getLocation = () => {
    Taro.getLocation({
      type: 'wgs84',   //默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标 
      success: function (res) {
        // success
        const { longitude, latitude } = res
      },
      fail: error => {
        const message = error.errMsg || error.message
        if (message === 'getLocation:fail auth deny') {
          // 拒接服务
          Taro.showModal({
            title: '请求授权当前位置',
            content: '该选项需要获取您的地理位置，请确认授权',
            confirmColor: '#fa9191',
            success: ({ cancel }) => {
              if (cancel) return
              this.openSetting()
            }
          })
        }
      }
    })
  }
  openSetting = () => {
    Taro.openSetting({
      success: result => {
        if (!result.authSetting['scope.userLocation']) return
        // 已经授权获取地理位置
        this.getLocation()
      }
    })
  }

  onAnimationFinish = e => {
    const { currentIndex } = this.state
    let lastTab = this.lastTab
    const nextTab = e.detail.current
    if (this.allowSwitch && nextTab === currentIndex) {
      // 划动了，但是没有划动到下一页
      return
    }
    if (nextTab === 2) {
      // 周边
      const location = Taro.getStorageSync('location')
      if (!location) {
        // 不存在信息
        this.getLocation()
      }
    }
    this.allowSwitch = true
    if (currentIndex !== nextTab) {
      // 说明是由 swiper 自己触发的切换
      lastTab = currentIndex
      this.state.currentIndex = nextTab
      this.setState({})
    }
  }

  init = () => {
    const { data, currentIndex } = this.state
    const currentPage = this.queryParams.currentPage - 1
    if (data[currentIndex] === void 0) {
      data[currentIndex] = []
    }
    const pArr = data[currentIndex]
    let arr = []
    for (let i = 0; i < this.queryParams.pageSize; i++) {
      arr.push({
        id: i,
        nickName: '曾小晨',
        avatar: 'http://q1.qlogo.cn/g?b=qq&nk=704729872&s=640',
        photos: new Array((Math.random() * 5 | 0) + 1).fill({ src: 'https://cdnst1.rryue.cn/photos/31388a70ac834cbbb7f80147e426a4c1.jpg' })
      })
    }
    pArr[currentPage] = arr
    if (!Array.isArray(this.boundings)) {
      this.boundings = []
    }
    this.setState({}, () => {
      Taro.createSelectorQuery().select(`#page${currentPage}`).boundingClientRect((rect) => {
        console.log(rect)
        this.boundings[currentPage] = {
          height: rect.height,//高度
          top: currentPage === 0 ? rect.top : this.boundings[currentPage - 1].top + this.boundings[currentPage - 1].height,// 上边界
          bottom: currentPage === 0 ? rect.bottom : this.boundings[currentPage - 1].bottom + rect.height // 下边界
        }
      }).exec()
    })
  }

  componentDidShow () {
    if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) {
      this.$scope.getTabBar().setData({
        selected: 0
      })
    }
  }

  componentDidMount () {
    this.init()
  }

  render () {
    const { currentIndex, tabs, data } = this.state
    return (
      <GRootPage scrollView={false} rootStyle={{ paddingBottom: 100 }}>
        {/* 其他功能按钮 */}
        <View className='home-tabs'>
          <GTabs data={tabs} current={currentIndex} onClick={this.onTabClick} />
        </View>
        <Swiper
          current={currentIndex}
          duration={200}
          onAnimationFinish={this.onAnimationFinish}
          className='scroll-y'
        >
          {
            tabs.map((tab, tIndex) => {
              const list = data[tIndex] || []
              return (
                <SwiperItem style={{ backgroundColor: '#f5f5f5' }}>
                  <ScrollView scrollY style={{ height: '100%' }} onScrollToLower={() => {
                    this.queryParams.currentPage++
                    this.init()
                  }}>
                    {
                      list.map((item, index) => (
                        <View id={'page' + index}>
                          <GCardList data={item} />
                        </View>
                      ))
                    }
                  </ScrollView>
                </SwiperItem>
              )
            })
          }
        </Swiper>
      </GRootPage>
    )
  }
}
